import {
  Card,
  Button,
  InputNumber,
  Space,
  Row,
  Col,
  message,
  Empty,
  Tabs,
  Tag,
} from "antd";
import {
  DeleteOutlined,
  FileTextOutlined,
  ShoppingCartOutlined,
} from "@ant-design/icons";
import { useDispatch, useSelector } from "react-redux";
import {
  removeGoods,
  changeGoodsNum,
  clearGoods,
  setCart,
} from "@/store/modules/cratStore";
import router from "@/router";
import { useEffect, useState } from "react";
import { Typography } from "antd";
import { removeGoodsApi, clearGoodsApi, getCartListApi } from "@/apis/cart";
import {
  createOrderByCartApi,
  getOrderDetailApi,
  getOrderListApi,
  getOrderItemApi,
} from "@/apis/order";

const STATUS_CONFIG = {
  0: { text: "待支付", color: "orange" },
  1: { text: "已完成", color: "blue" },
  2: { text: "已完成", color: "green" },
  3: { text: "已取消", color: "red" },
  4: { text: "已退款", color: "purple" },
  // 可根据需要扩展其他状态
};

export default function CartPage() {
  const dispatch = useDispatch();
  const cart = useSelector((state: any) => state.cart.cart);

  const [orders, setOrders] = useState([]);
  const [active, setActive] = useState("1");
  const [visible, setVisible] = useState(false);

  // 获取订单
  async function getOrderList() {
    try {
      const res: any = await getOrderListApi({ page: 1, size: 10 });
      if (res.code === 0) {
        setOrders(res.data.records);
      } else {
        message.error("获取订单列表失败");
      }
    } catch (error) {
      message.error("请求失败");
    }
  }

  // 移除商品
  async function RemoveGood(id: any) {
    const formData = new FormData();
    formData.append("gameId", id);
    try {
      const res: any = await removeGoodsApi(formData);
      if (res.code === 0) {
        message.success("已移除商品");
        dispatch(removeGoods(id));
      } else {
        message.error("移除商品失败");
      }
    } catch (error) {
      message.error("请求失败");
    }
  }

  // 获取购物车列表
  async function getCartList() {
    try {
      const res: any = await getCartListApi();
      if (res.code === 0) {
        dispatch(setCart(res.data));
      }
    } catch (error) {}
  }

  // 结算
  async function settlement() {
    try {
      const res: any = await createOrderByCartApi();
      if (res.code === 0) {
        message.success("创建订单成功");
        message.success("结算成功！");
        dispatch(clearGoods());
        setActive("2");
        await getOrderList();
      } else {
        message.error("创建订单失败");
      }
    } catch (error) {
      message.error("请求失败");
    }
  }

  useEffect(() => {
    getOrderList();
    getCartList();
  }, []);

  // 日期格式化函数
  const formatDate = (timestamp: any) => {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${(date.getMonth() + 1)
      .toString()
      .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")} ${date
      .getHours()
      .toString()
      .padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`;
  };

  const OrderCard = () => {
    return (
      <div style={{ maxWidth: "100%", margin: "0 auto" }}>
        {orders.map((order: any) => (
          <Card
            key={order.orderCode}
            style={{
              marginBottom: 16,
              borderRadius: 8,
              boxShadow: "0 2px 8px rgba(0,0,0,0.09)",
            }}
          >
            {/* 订单头部 */}
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                marginBottom: 12,
              }}
            >
              <div>
                <div style={{ color: "rgba(0,0,0,0.45)" }}>
                  订单编号：{order.orderCode}
                </div>
                <div style={{ color: "rgba(0,0,0,0.45)", fontSize: 12 }}>
                  下单时间：{formatDate(order.createTime)}
                </div>
              </div>
              <Tag
                color={STATUS_CONFIG[order.status as 0 | 1 | 2 | 3 | 4].color}
              >
                {STATUS_CONFIG[order.status as 0 | 1 | 2 | 3 | 4].text}
              </Tag>
            </div>

            {/* 商品展示区域 */}
            <div
              style={{
                border: "1px solid #f0f0f0",
                borderRadius: 8,
                marginBottom: 12,
                padding: 12,
              }}
            >
              {order.orderItems?.map((item: any) => (
                <div
                  key={item.id}
                  style={{
                    display: "flex",
                    gap: 16,
                    padding: 8,
                    borderBottom: "1px solid #f0f0f0",
                  }}
                >
                  {/* 游戏封面 */}
                  <img
                    src={item.coverImage || "https://via.placeholder.com/80"}
                    alt={item.title}
                    style={{
                      width: 80,
                      height: 100,
                      objectFit: "cover",
                      borderRadius: 4,
                    }}
                  />

                  {/* 商品信息 */}
                  <div style={{ flex: 1 }}>
                    <div
                      style={{
                        fontWeight: 500,
                        marginBottom: 4,
                        fontSize: 15,
                      }}
                    >
                      {item.title}
                    </div>

                    {/* 价格展示 */}
                    <div
                      style={{
                        display: "flex",
                        gap: 8,
                        alignItems: "baseline",
                      }}
                    >
                      {item.priceD !== item.price && (
                        <span
                          style={{
                            color: "#999",
                            textDecoration: "line-through",
                            fontSize: 12,
                          }}
                        >
                          ¥{item.price.toFixed(2)}
                        </span>
                      )}
                      <span
                        style={{
                          color: "#ff4d4f",
                          fontWeight: 500,
                          fontSize: 16,
                        }}
                      >
                        ¥{item.priceD?.toFixed(2) || item.price.toFixed(2)}
                      </span>
                    </div>

                    {/* 其他信息 */}
                    <div
                      style={{
                        color: "#666",
                        fontSize: 12,
                        marginTop: 8,
                        lineHeight: 1.4,
                      }}
                    >
                      {item.description}
                    </div>
                  </div>
                </div>
              ))}
            </div>

            {/* 订单摘要 */}
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                padding: "12px 0",
                borderTop: "1px solid #f0f0f0",
                borderBottom: "1px solid #f0f0f0",
                margin: "12px 0",
              }}
            >
              <div>
                <span style={{ color: "#ff4d4f", fontWeight: 500 }}>
                  实付金额：¥{order.orderTotalAmount.toFixed(2)}
                </span>
              </div>
              <div style={{ color: "rgba(0,0,0,0.45)", fontSize: 12 }}>
                最近更新：{formatDate(order.updateTime)}
              </div>
            </div>

            {/* 操作按钮 */}
            <div
              style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}
            >
              {order.status === 0 && (
                <Button type="primary" size="small">
                  去支付
                </Button>
              )}
              {/* {order.status === 1 && <Button size="small">查看物流</Button>} */}
              {/* <Button size="small">查看详情</Button> */}
            </div>
          </Card>
        ))}
      </div>
    );
  };

  const items = [
    {
      key: "1",
      label: "购物车",
      children: (
        // {/* 购物车商品列表 */}
        <div style={{ flex: 1, marginBottom: "24px" }}>
          {cart.length === 0 ? (
            <Empty description="购物车是空的" style={{ marginTop: 100 }}>
              <Button type="primary" onClick={() => router.navigate("/game")}>
                去逛逛
              </Button>
            </Empty>
          ) : (
            cart.map((item: any) => (
              <div
                key={item.gameId}
                style={{
                  marginBottom: "16px",
                  borderRadius: "8px",
                  padding: "1em",
                  backgroundColor: "rgba(40,40,40,0.8)",
                }}
              >
                <Row align="middle" gutter={16}>
                  <Col span={4}>
                    <img
                      src={item.coverImage}
                      alt={item.title}
                      style={{ width: "100%", borderRadius: "4px" }}
                      onClick={() =>
                        router.navigate(`/game/game_info/${item.gameId}`)
                      }
                    />
                    <Typography.Text style={{ color: "#fff" }}>
                      {item.title}
                    </Typography.Text>
                  </Col>

                  <Col span={14}>
                    <h3 style={{ marginBottom: "8px" }}>{item.name}</h3>
                    <Space size="large">
                      {item.priceD ? (
                        <>
                          <span
                            style={{ color: "#ff4d4f", fontWeight: "bold" }}
                          >
                            ¥{item.priceD}
                          </span>
                          <span
                            style={{
                              textDecoration: "line-through",
                              color: "#999",
                            }}
                          >
                            ¥{item.price}
                          </span>
                        </>
                      ) : (
                        <span style={{ color: "#ff4d4f", fontWeight: "bold" }}>
                          ¥{item.price}
                        </span>
                      )}
                    </Space>
                  </Col>

                  <Col span={6}>
                    <Space size="middle" align="center">
                      <InputNumber
                        min={1}
                        max={1}
                        value={item.quantity}
                        onChange={(value) => {
                          if (typeof value === "number") {
                            dispatch(
                              changeGoodsNum({
                                id: item.gameId,
                                quantity: value,
                              })
                            );
                          }
                        }}
                      />
                      <Button
                        danger
                        icon={<DeleteOutlined />}
                        onClick={() => RemoveGood(item.gameId)}
                      />
                    </Space>
                  </Col>
                </Row>
              </div>
            ))
          )}
        </div>
      ),
    },
    {
      key: "2",
      label: "订单记录",
      children:
        orders.length === 0 ? (
          <Empty description="暂无订单记录" style={{ marginTop: 100 }}></Empty>
        ) : (
          <OrderCard />
        ),
    },
  ];

  // 计算总价
  const total = cart.reduce(
    (sum: any, item: any) => sum + (item.priceD || item.price) * item.quantity,
    0
  );

  return (
    <div
      style={{
        padding: "24px",
        maxWidth: "100%",
        margin: "0 auto",
        minHeight: "calc(100vh - 48px)",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <h2 style={{ marginBottom: "24px" }}>
        {active === "1" ? <ShoppingCartOutlined /> : <FileTextOutlined />}

        {active === "1" ? " 购物车" : " 订单记录"}
      </h2>
      <Tabs
        defaultActiveKey={active}
        items={items}
        onTabClick={(key) => setActive(key)}
      ></Tabs>

      {/* 结算栏 */}
      {active === "1" && cart.length > 0 && (
        <div
          style={{
            position: "sticky",
            marginLeft: "auto",
            width: "400px",
            bottom: "5px",
            boxShadow: "0 -2px 10px rgba(0,0,0,0.1)",
            zIndex: 1,
          }}
        >
          <Row justify="end" gutter={16}>
            <Col>
              <Card
                style={{
                  borderRadius: "8px",
                  width: "400px",
                  padding: "12px",
                  backgroundColor: "rgba(50,50,50,0.8)",
                  border: "none",
                  marginRight: "1em",
                }}
              >
                <Row justify="space-between" align="middle">
                  <Col>
                    <Space direction="vertical" size={0}>
                      <div style={{ fontWeight: "bold" }}>
                        总计:{" "}
                        <span style={{ color: "#ff4d4f" }}>
                          ¥{total.toFixed(2)}
                        </span>
                      </div>
                      <div style={{ fontSize: 12, color: "#999" }}>
                        共{cart.length}件商品
                      </div>
                    </Space>
                  </Col>
                  <Col>
                    <Button
                      type="primary"
                      danger
                      size="large"
                      style={{ height: "40px", width: "120px" }}
                      onClick={settlement}
                    >
                      去结算
                    </Button>
                  </Col>
                </Row>
              </Card>
            </Col>
          </Row>
        </div>
      )}
    </div>
  );
}
